package com.example.live.vm

import androidx.lifecycle.viewModelScope
import com.example.common.vm.BaseViewModel
import com.example.live.intent.LiveViewIntent
import com.example.live.repo.LiveRepository
import com.example.live.state.LiveUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch

@HiltViewModel
class LiveViewModel: BaseViewModel<LiveViewIntent>() {
    private val repository: LiveRepository = LiveRepository()
    private val _uiStateFlow = MutableSharedFlow<LiveUiState>()
    val uiStateFlow : SharedFlow<LiveUiState> = _uiStateFlow.asSharedFlow()

    override fun dispatchIntent(intent: LiveViewIntent) {
        when (intent) {
            is LiveViewIntent.LoadRecommendSimpleVideo -> loadRecommendSimpleVideo(intent.page, intent.pageSize)
            is LiveViewIntent.LoadGoodsInfo-> loadGoodsInfo(intent.category_id, intent.currentPage, intent.pageSize, intent.room_id)
            is LiveViewIntent.userLiveRoom-> UserLiveRoom()
        }
    }

    private fun loadGoodsInfo(categoryId: Int, currentPage: Int, pageSize: Int, roomId: String) {
        mViewModelScope.launch(mDispatcher) {
            repository.getGoodsInfo(categoryId, currentPage,pageSize,roomId).collect{ list ->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(LiveUiState.LoadGoodsInfoSuccess(list))
                } else {
                    _uiStateFlow.emit(LiveUiState.LoadGoodsInfoFail("没有获取到商品列表！"))
                }
            }
        }
    }

    private fun loadRecommendSimpleVideo(page: Int, pageSize: Int) {
        mViewModelScope.launch(mDispatcher) {
            repository.getRecommendVideo(page, pageSize).collect{ list ->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(LiveUiState.LoadSimpleVideoSuccess(list))
                } else {
                    _uiStateFlow.emit(LiveUiState.LoadSimpleVideoFail("没有获取到推荐视频！"))
                }
            }
        }
    }
    private fun UserLiveRoom() {
        mViewModelScope.launch(mDispatcher) {
            repository.userLiveRoom().collect { list ->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(LiveUiState.userLiveRoomSuccess(list))
                }else{
                    _uiStateFlow.emit(LiveUiState.userLiveRoomFail("异常！！！排行榜"))
                }
            }
        }
    }

}